from django.core.management.base import BaseCommand
from django.contrib.auth.hashers import make_password
from user.models import User, Role
import hashlib


class Command(BaseCommand):
    help = '创建测试用户用于BOSS智能招聘助手'

    def handle(self, *args, **options):
        # 创建或获取角色
        role, created = Role.objects.get_or_create(
            name='hr',
            defaults={'name': 'hr'}
        )
        
        if created:
            self.stdout.write(self.style.SUCCESS(f'创建角色: {role.name}'))
        else:
            self.stdout.write(f'使用现有角色: {role.name}')

        # 创建测试用户
        test_phone = '13800138000'
        test_password = '123456'
        
        # 检查用户是否已存在
        if User.objects.filter(phone=test_phone).exists():
            self.stdout.write(f'测试用户 {test_phone} 已存在')
            return

        # 创建用户
        user = User.objects.create(
            phone=test_phone,
            username='测试用户',
            email='test@boss.com',
            password_hash=make_password(test_password),
            status=True,
            role=role
        )
        
        self.stdout.write(
            self.style.SUCCESS(
                f'成功创建测试用户:\n'
                f'手机号: {test_phone}\n'
                f'密码: {test_password}\n'
                f'角色: {role.name}'
            )
        )
        
        # 创建额外的测试用户
        additional_users = [
            {'phone': '13900139000', 'username': 'HR用户', 'role_name': 'hr'},
            {'phone': '13700137000', 'username': '求职者', 'role_name': '普通求职'},
        ]
        
        for user_data in additional_users:
            role_name = user_data['role_name']
            role_obj, _ = Role.objects.get_or_create(name=role_name)
            
            if not User.objects.filter(phone=user_data['phone']).exists():
                User.objects.create(
                    phone=user_data['phone'],
                    username=user_data['username'],
                    email=f"{user_data['phone']}@boss.com",
                    password_hash=make_password('123456'),
                    status=True,
                    role=role_obj
                )
                self.stdout.write(
                    self.style.SUCCESS(
                        f'创建用户: {user_data["username"]} ({user_data["phone"]})'
                    )
                )
